package com.lingyun.framework.security;

import com.lingyun.common.vo.LoginUser;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
/**
 *
 * @author 没事别学JAVA
 *
 */
@Component
public class SelfAuthenticationProvider implements AuthenticationProvider {

    @Resource
    private UserDetailsService userDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {


        /** 这个获取表单输入中返回账号*/
        String userName = (String) authentication.getPrincipal();

        /** 这个是表单中输入的密码 */
        String password = (String) authentication.getCredentials();

        /** 根据表单用户账号 查找用户信息 */
        LoginUser loginUser = (LoginUser) userDetailsService.loadUserByUsername(userName);


        /** 判断表单中的密码和数据库中的密码是否一致 */
        PasswordEncoder passwordEncoder=new BCryptPasswordEncoder();
        if (!passwordEncoder.matches(password,loginUser.getLyUser().getPassword())) {
            throw new BadCredentialsException("");
        }

        return new UsernamePasswordAuthenticationToken(loginUser, loginUser.getPassword(), loginUser.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return aClass.equals(UsernamePasswordAuthenticationToken.class);
    }

}
